package net.elive.server;

import java.io.IOException;
import java.net.DatagramPacket;

import net.elive.common.p2pnet.message.RegisterMessage;
import net.elive.common.p2pnet.message.RegisterMessageBack;
import net.elive.tools.MessageCheck;
import net.elive.tools.MessageType;
import net.elive.tools.RandomNum;
import net.elive.utils.LogUtils;

import org.apache.commons.logging.Log;

/**
 * 消息接收进程
 * 
 * @author jin_cool.cao
 * 
 */
public class MessageProcessor implements Runnable {
	Log log = LogUtils.getLog(MessageProcessor.class);
	Thread thread;

	/**
	 * 消息进程
	 */
	public MessageProcessor() {
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		while (true) {
			DatagramPacket dp = Config.messageReceiver.getPacket();
			if (dp != null) {
				if (MessageCheck.checkVersion(dp) == Config.version) {
					int sType = MessageCheck.checkSType(dp);
					/**
					 * 登陆
					 */
					if (sType == MessageType.STYPE_REGMESSAGE) {
						log.info(">>>>>>>>>>>消息注册中>>>>>>>>>>>>IP地址来源:"
								+ dp.getAddress());
						RegisterMessage regMessage = new RegisterMessage(dp);
						int sessionId = RandomNum.randomInt(); // 随机产生一个sessionId;
						Config.nodeManage.addNode(dp.getAddress(), sessionId,
								regMessage.getNodeType(),
								regMessage.getRoutePort(), regMessage.getDbServerPort(),
								regMessage.getAssistServerPort());
						log.info(">>>>>>>>>注册成功>>>>>>>>");
						RegisterMessageBack regSimple = new RegisterMessageBack();
						regSimple.setDestnationAddress(dp.getAddress());
						regSimple.setDestnationPort(dp.getPort());
						regSimple.setSessionId(sessionId);
						try {
							Config.ds.send(regSimple.getDatagramPacket());		//发生数据包
						} catch (IOException e) {
							log.equals(">>>>>>>发生数据包失败>>>>>>>");
							e.printStackTrace();
						}
						log.info(">>>>>>>>登录>>>>IP地址:"+dp.getAddress()+"Session:"+sessionId);
					}
				}
			}

		}
	}

}
